package com.youhong.teethcare.utils;

import android.util.Log;

import org.apache.http.NameValuePair;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Administrator on 2017/5/8.
 */

public class StringableHashMap extends HashMap<String, String> {


    @Override
    public String toString() {

        StringBuffer buffer = new StringBuffer();

        // String current_key = null;
        ArrayList<String> list = new ArrayList<>();
        Iterator<String> iterator = super.keySet().iterator();
        HashMap<String, Object> unique_keep = new HashMap<>();


        while (iterator.hasNext()) {
            list.add(iterator.next());
        }

        for (int i = 0; i < list.size(); i++) {

            String temp = null;

            for (int j = 0; j < list.size(); j++) {

                String current_key = list.get(j);

                if (temp == null) {

                    if (unique_keep.containsKey(current_key)) {

                        continue;

                    } else {

                        temp = current_key;
                    }

                } else if (!unique_keep.containsKey(current_key) &&
                        compare(current_key, temp) == LESS
                        ) {


                    temp = current_key;
                }
            }

            unique_keep.put(temp, null);
            buffer.append(temp);
            buffer.append("=");
            buffer.append(super.get(temp));

            if (i + 1 < size()) {
                buffer.append("&");
            }

        }

        Log.e("abc", buffer.toString());

        return buffer.toString();

    }

    public StringableHashMap addIn(List<NameValuePair> list) {

        for (NameValuePair valuePair : list) {

            put(valuePair.getName(), valuePair.getValue());

        }

        return this;
    }



    private static final int LESS = -1;
    private static final int BIG = 1;
    private static final int EQUAL = 0;

    private int compare(String str1, String str2) {
        //     int result = 0;
        for (int i = 0; i < Math.min(str1.length(), str2.length()); i++) {

            if (str1.toLowerCase().charAt(i) == str2.toLowerCase().charAt(i)) {


            } else {

                if (str1.toLowerCase().charAt(i) < str2.toLowerCase().charAt(i)) {

                    return LESS;

                } else {

                    return BIG;

                }


            }

        }

        return EQUAL;
    }
}
